package com.tcfvic.client.panels.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.tcfvic.client.PersonService;
import com.tcfvic.client.PersonServiceAsync;
import com.tcfvic.client.panels.widgets.addons.advancedtable.AdvancedTable;
import com.tcfvic.client.panels.widgets.addons.advancedtable.RowSelectionListener;
import com.tcfvic.client.pojos.Rto;
import com.tcfvic.client.tools.State;
import com.tcfvic.client.tools.Tools;

public class RTODetailsInputWidget extends FlexTable implements
		RowSelectionListener {
	private TextBox rtoId = new TextBox();
	private TextBox nameTB = new TextBox();
	private TextBox contactNameTB = new TextBox();
	private TextBox campus = new TextBox();
	private TextArea notesTA = new TextArea();
	private TextBox position = new TextBox();
	private TextBox tel1 = new TextBox();
	private TextBox tel2 = new TextBox();
	private TextBox rtoFax = new TextBox();
	private TextBox rtoPhone= new TextBox();
	private TextBox email = new TextBox();
	private TextBox street1 = new TextBox();
//	private TextBox street2 = new TextBox();
	private ListBox state = new ListBox();
	private TextBox suburb = new TextBox();
	private TextBox postcode = new TextBox();
	private TextBox website = new TextBox();
	private RTODetailsListWidget list = null;

	/**
	 * Create a remote service proxy to talk to the server-side CompanyDetails
	 * service.
	 */
	private final PersonServiceAsync personService = GWT
			.create(PersonService.class);

	public RTODetailsInputWidget() {
		super();

		// Create a table to layout the form options
		setCellSpacing(4);
		setWidth("100%");
		FlexCellFormatter cellFormatter = getFlexCellFormatter();

		// Add a title to the form
		setHTML(0, 0, "Add/Edit RTO data");
		cellFormatter.setColSpan(0, 0, 4);
		cellFormatter.setHorizontalAlignment(0, 0,
				HasHorizontalAlignment.ALIGN_CENTER);

		// Add some standard form options
		int rowNum = 1;
		setHTML(rowNum, 0, "RTO name");
		setWidget(rowNum, 1, nameTB);
		setHTML(rowNum, 2, "RTO fax");
		setWidget(rowNum++, 3, rtoFax);

		setHTML(rowNum, 0, "RTO campus");
		setWidget(rowNum, 1, campus);
		setHTML(rowNum, 2, "RTO phone");
		setWidget(rowNum++, 3, rtoPhone);
		
		setHTML(rowNum, 0, "Contact");
		setWidget(rowNum, 1, contactNameTB);
		setHTML(rowNum, 2, "Street");
		setWidget(rowNum++, 3, street1);

		setHTML(rowNum, 0, "Position");
		setWidget(rowNum, 1, position);
		setHTML(rowNum, 2, "Suburb");
		setWidget(rowNum++, 3, suburb);


		setHTML(rowNum, 0, "Contact phone");
		setWidget(rowNum, 1, tel1);
		setHTML(rowNum, 2, "State");
		state = Tools.getStatesListBox();
		setWidget(rowNum++, 3, state);

		setHTML(rowNum, 0, "Contact mobile");
		setWidget(rowNum, 1, tel2);
		setHTML(rowNum, 2, "Postcode");
		setWidget(rowNum++, 3, postcode);

		setHTML(rowNum, 0, "Email");
		setWidget(rowNum, 1, email);
		setHTML(rowNum, 2, "Notes");
		notesTA.setVisibleLines(5);
		setWidget(rowNum++, 3, notesTA);

		setHTML(rowNum, 0, "Website");
		setWidget(rowNum++, 1, website);

		
		final Button saveButton = new Button("Save");
		saveButton.getElement().setId("saveButton");
		setWidget(rowNum, 4, saveButton);

		// Add a handler to close the DialogBox
		saveButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				saveRTODetails();
			}
		});

		clearAllFields();
	}

	public void addRTODetailsList(RTODetailsListWidget list) {
		this.list = list;
	}

	public ListBox getStatesListBox() {
		final ListBox dropBox = new ListBox(false);

		dropBox.addItem("");
		for (State state : State.values()) {
			dropBox.addItem(state.getState());
		}
		return dropBox;
	}

	private boolean validInput() {
		if (rtoId.getText() != null && rtoId.getText().trim().equals("-1")) {
			Integer.parseInt(rtoId.getText());
			new SimpleMessagePopup(
					"Please select a RTO before trying to edit details", null)
					.showPopup();
			return false;
		}
		return true;
	}

	public void createNewRecord() {
		clearAllFields();
		rtoId.setText("");
	}

	public void clearAllFields() {
		rtoId.setText("-1");
		nameTB.setText("");
		contactNameTB.setText("");
		campus.setText("");
		notesTA.setText("");
		position.setText("");
		tel1.setText("");
		tel2.setText("");
		rtoFax.setText("");
		rtoPhone.setText("");
		email.setText("");
		street1.setText("");
		website.setText("");
//		street2.setText("");
		Tools.resetList(state);
		suburb.setText("");
		postcode.setText("");
	}

	@Override
	public void onRowSelected(AdvancedTable sender, String rowId) {
		clearAllFields();
		personService.getRTO(Integer.valueOf(rowId), new AsyncCallback<Rto>() {
			@Override
			public void onSuccess(Rto result) {
				rtoId.setText(String.valueOf(result.getId()));
				nameTB.setText(result.getName());
				contactNameTB.setText(result.getContactName());
				campus.setText(result.getCampus());
				notesTA.setText(result.getNotes());
				position.setText(result.getContactPosition());
				tel1.setText(result.getTel1());
				tel2.setText(result.getTel2());
				rtoFax.setText(result.getRtoFax());
				rtoPhone.setText(result.getRtoPhone());
				email.setText(result.getEmail());
				street1.setText(result.getStreet1());
//				street2.setText(result.getStreet2());
				state.setSelectedIndex(Tools.getSelectedIndex(state, result
						.getState()));
				suburb.setText(result.getSuburb());
				postcode.setText(result.getPostcode());
				website.setText(result.getWebsite());
			}

			@Override
			public void onFailure(Throwable caught) {
				System.err.println("Error occured returning the rto details: "
						+ caught);
				new SimpleMessagePopup(
						"The rto's record was not retrieved due to an internal error",
						null).showPopup();
			}
		});
	}

	private void saveRTODetails() {
		try {
			if (!validInput()) {
				return;
			}

			Rto rto = new Rto();
			if (rtoId != null && rtoId.getText().trim().length() > 0) {
				rto.setId(new Integer(rtoId.getText()));
			}

			rto.setName(nameTB.getText());
			rto.setContactName(contactNameTB.getText());
			rto.setCampus(campus.getText());
			rto.setNotes(notesTA.getText());
			rto.setContactPosition(position.getText());
			rto.setTel1(tel1.getText());
			rto.setTel2(tel2.getText());
			rto.setRtoFax(rtoFax.getText());
			rto.setRtoPhone(rtoPhone.getText());
			rto.setEmail(email.getText());
			rto.setStreet1(street1.getText());
//			rto.setStreet2(street2.getText());
			try {
				rto.setState(state.getItemText(state.getSelectedIndex()));
			} catch (Exception e) {
				// ignore
			}
			rto.setSuburb(suburb.getText());
			rto.setPostcode(postcode.getText());
			rto.setWebsite(website.getText());

			personService.saveRTO(rto, new AsyncCallback<Void>() {
				@Override
				public void onSuccess(Void result) {
					System.out
							.println("Successfully wrote rto record to dbase");
					clearAllFields();
					if (list != null) {
						list.updateTableData();
					}
					new SimpleMessagePopup("RTO saved successfully", null)
							.showPopup();
				}

				@Override
				public void onFailure(Throwable caught) {
					System.err
							.println("Error occured writing rto details to database in "
									+ "CompanyDetailsInputWidget.saveRTODetails: "
									+ caught);
					new SimpleMessagePopup(
							"The RTO was not saved due to an internal error",
							null).showPopup();
				}
			});
		} catch (Exception e) {
			new SimpleMessagePopup("An error occured saving the RTO details: "
					+ e, null).showPopup();
		}
	}

}
